package network;

import service.ProductService;
import service.UserService;
import model.User;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

public class EStoreServer {
    private ProductService productService = new ProductService();
    private UserService userService = new UserService();
    private ServerSocket serverSocket;
    private final int PORT = 8888;

    public void start() {
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("服务器已启动，监听端口：" + PORT);

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("收到客户端连接：" + clientSocket);
                new Thread(() -> handleClient(clientSocket)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleClient(Socket clientSocket) {
        try (ObjectInputStream ois = new ObjectInputStream(clientSocket.getInputStream());
             ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream())) {

            String request = (String) ois.readObject();
            System.out.println("收到请求：" + request);

            switch (request) {
                case "GET_ALL_PRODUCTS":
                    oos.writeObject(productService.getAllProducts());
                    break;
                case "USER_LOGIN":
                    String username = (String) ois.readObject();
                    String password = (String) ois.readObject();
                    User user = userService.login(username, password);
                    oos.writeObject(user);
                    break;
                case "ADMIN_GET_ALL_USERS":
                    List<User> users = userService.getAllUsers();
                    oos.writeObject(users);
                    break;
                default:
                    oos.writeObject("未知请求");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        new EStoreServer().start();
    }
}